﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using Dal;
using System.Collections;
using Indexing;

namespace QueryRunning
{
    /// <summary>
    /// QueryRunner's job is to run all queries in the system after an update cycle,
    /// then update the DB with relevant results for each user.
    /// </summary>
    public class QueryRunner
    {
        public Hashtable QueryUsers; //< query (string), user list (List<User>) >
        string _connectionString;
        Catalog _catalog;
       

        public QueryRunner(string ConnectionString, Catalog Catalog)
        {
            _connectionString = ConnectionString;
            QueryUsers = GetQueryUsersHash();
            _catalog = Catalog;
        }

        private Hashtable GetQueryUsersHash()
        {
            DatabaseAbstractionLayer _dal = new DatabaseAbstractionLayer(_connectionString);
            Hashtable queryUsers = new Hashtable();
            // get all queries.
            List<string> Queries = _dal.GetQueries();
            foreach (string query in Queries)
            {
                List<User> usersOfQuery = _dal.GetUsersForQuery(query);
                if (usersOfQuery.Count > 0) 
                  queryUsers.Add(query, usersOfQuery);
            }
            return queryUsers;
        }

        /// <summary>
        /// Runs all queries, updating DB with appropriate user results.
        /// </summary>
        /// <returns>A List of usernames who require notifications.</returns>
        public List<string> RunAllUserQueries() 
        {
            DatabaseAbstractionLayer _dal = new DatabaseAbstractionLayer(_connectionString);
            Searching.Searcher Searcher = new Searching.Searcher();
         
            List<string> userNameList = new List<string>();

            foreach (DictionaryEntry queryUserList in QueryUsers)
            {
                //get results for this query.
                List<Document> results = Searcher.DoSearch(queryUserList.Key as string,
                    _catalog);
                if (results.Count == 0) 
                    continue;
                //Now distribute results to relevant users and notify them.
                foreach (User user in queryUserList.Value as List<User>)
                {
                    _dal.InsertUserQueryResults(user, queryUserList.Key as string, results);
                    if (!userNameList.Contains(user.UserName))
                        userNameList.Add(user.UserName);
                    //Notifier.NotifyUser(user);
                   
                }
            }
            return userNameList;
        }

    }
}
